package com.yanxx.codegenerator.storage.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanxx.codegenerator.storage.CodeGeneratorState;
import com.yanxx.codegenerator.storage.CodeGeneratorStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * 基于文件的编码生成器存储实现
 */
public class FileStorage implements CodeGeneratorStorage {
    private static final Logger logger = LoggerFactory.getLogger(FileStorage.class);
    
    private final String filePath;
    private final ObjectMapper objectMapper;
    
    public FileStorage(String filePath) {
        this.filePath = filePath;
        this.objectMapper = new ObjectMapper();
    }
    
    @Override
    public boolean save(long currentMaxValue, Set<String> confirmedCodes, Set<String> pendingCodes, Set<String> recycledCodes) {
        try {
            CodeGeneratorState state = new CodeGeneratorState(currentMaxValue, confirmedCodes, pendingCodes, recycledCodes);
            objectMapper.writeValue(new File(filePath), state);
            logger.info("Successfully saved code generator state to file: {}", filePath);
            return true;
        } catch (IOException e) {
            logger.error("Failed to save code generator state to file: {}", filePath, e);
            return false;
        }
    }
    
    @Override
    public CodeGeneratorState load() {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.info("State file does not exist: {}, returning empty state", filePath);
            return new CodeGeneratorState();
        }
        
        try {
            CodeGeneratorState state = objectMapper.readValue(file, CodeGeneratorState.class);
            logger.info("Successfully loaded code generator state from file: {}", filePath);
            return state;
        } catch (IOException e) {
            logger.error("Failed to load code generator state from file: {}", filePath, e);
            return new CodeGeneratorState();
        }
    }
    
    @Override
    public boolean clear() {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.info("State file does not exist: {}, nothing to clear", filePath);
            return true;
        }
        
        boolean deleted = file.delete();
        if (deleted) {
            logger.info("Successfully cleared code generator state file: {}", filePath);
        } else {
            logger.error("Failed to clear code generator state file: {}", filePath);
        }
        
        return deleted;
    }
}